package com.czn.bookshop.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czn.bookshop.entity.User;
import com.czn.bookshop.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * 用户Service业务层
 *
 * @author ChenZeNan
 * @create 2020-12-27 12:43
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    UserMapper userMapper;

    public String checkUsername(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            return "0"; // 用户不存在
        } else {
            return "1"; // 用户已存在
        }
    }

    public String loginUser(User loginUser, HttpSession session) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", loginUser.getUsername());
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            return "0"; //用户不存在
        } else {
            if (user.getPassword().equals(loginUser.getPassword())) {
                // 登陆后将用户信息放入session中
                session.setAttribute("user", user);
                return "1"; // 用户存在，并且密码正确
            } else {
                return "2"; //用户存在，但是密码输错了
            }
        }
    }
}
